import axios from "axios";
import { Message } from "element-ui";
import { getToken } from "@/utils/auth";
import baseURL from './baseURL';

// axios.defaults.withCredentials = true;
const amaxios = axios.create({
  baseURL: `${baseURL.agrLoginUrl}`,
  // baseURL: '/api',
  timeout: 30000 // 请求超时时间
});

// request interceptor
amaxios.interceptors.request.use(
  config => {
    config.headers["sysDataBaseName"] = "DB_TDW1_PUBLIC";
    config.headers["Content-Type"] = "application/json;charset=UTF-8";
    return config;
  },
  error => {
    console.log(error);
    return Promise.reject(error);
  }
);

// response interceptor
amaxios.interceptors.response.use(
  response => {
    const res = response.data;
    console.log(res, response)
    if (response.status !== 200) {
      Message({
        message: response.message,
        type: "error",
        duration: 5 * 1000
      });
    }
    return res;
  },
  error => {
    console.log("err" + error);
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);
// 封装get请求
export function get(url, params = {}, base = {}) {
  params.t = new Date().getTime(); // get方法加一个时间参数,解决ie下可能缓存问题.
  return amaxios({
    url: url,
    method: "get",
    params,
    base
  });
}

// 封装post请求
export function post(url, data = {}, base = {}) {
  // 默认配置
  let sendObject = {
    url: url,
    method: "post",
    cache: false,
    data,
    base
  };
  sendObject.data = JSON.stringify(data);
  // console.log(base)
  return amaxios(sendObject);
}
// 封装get请求
export function request(type, url, params = {}) {
  // params.t = new Date().getTime(); // get方法加一个时间参数,解决ie下可能缓存问题.
  return amaxios({
    url: url,
    method: type,
    data: params
  });
}
export default {
  get: get,
  post: post,
  request: request,
  amaxios
};
